package BIO;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author:谢君臣
 * @Date:2021/7/25-22:11
 * @version:1.0
 * @function:
 */
public class FileServer1 {
    private String filePath;
    private static int port;
    private static InetAddress inetAddress;
    static{
        port = 9999;
        try {
            inetAddress =InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public void save() throws IOException {
        String fileName = new String(UUID.randomUUID().toString());
        ServerSocket socket = new ServerSocket(port,0,inetAddress);
        Socket accept = socket.accept();
        DataInputStream dataInputStream = new DataInputStream(accept.getInputStream());
        //读取UTF类型的值（一般要和 writeUTF() 方法配套使用）否则会抛出异常
        String suffix = dataInputStream.readUTF();
        System.out.println("头文件后缀是：" + suffix);
        filePath += fileName +"."+ suffix;
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);

        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = dataInputStream.read(buffer))!=-1) {
            fileOutputStream.write(buffer,0,length);
            fileOutputStream.flush();
        }

        accept.getOutputStream().write(filePath.getBytes(StandardCharsets.UTF_8));
        accept.shutdownOutput();// 提示接收方，数据传输完毕
        fileOutputStream.close();
        dataInputStream.close();
        accept.close();
    }
}
